/**
 * Copyright 2012 Brigham Young University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.byu.nlp.cluster;

import edu.byu.nlp.cluster.em.AlternatingEM;
import edu.byu.nlp.cluster.em.AlternatingEMAble;
import edu.byu.nlp.cluster.em.ClusteringAndPredictiveModels;
import edu.byu.nlp.cluster.em.ExpectationMaximization.ParameterPair;
import edu.byu.nlp.cluster.em.HyperParameterOptimizer;
import edu.byu.nlp.cluster.em.ParameterInitializer;
import edu.byu.nlp.math.optimize.ValueAndObject;

/**
 * An EM-based Clusterer (or related, e.g., variational Bayes) for MAP estimation of the parameters of a mixture
 * model.
 * 
 * @author rah67
 *
 */
public class AlternatingEMClusterer<H, P> implements ProbabilisticClusterer {

	private final AlternatingEM aem;
	private final ParameterInitializer<H> hpInitializer;
	private final ParameterInitializer<P> initializer;
	private final AlternatingEMAble<H, P> altEMAble;
	private final HyperParameterOptimizer<H, P> optimizer;

	public AlternatingEMClusterer(AlternatingEM aem, ParameterInitializer<H> hpInitializer,
			ParameterInitializer<P> initializer, AlternatingEMAble<H, P> altEMAble,
			HyperParameterOptimizer<H, P> optimizer) {
		this.aem = aem;
		this.hpInitializer = hpInitializer;
		this.initializer = initializer;
		this.altEMAble = altEMAble;
		this.optimizer = optimizer;
	}

	@Override
	public ProbabilisticClustering cluster(Dataset data, int numClusters) {
		H initialHyperParams = hpInitializer.initialize(data, numClusters);
		H nextHyperParams = hpInitializer.initialize(data, numClusters);
		ParameterPair<H> hyperPair = new ParameterPair<H>(initialHyperParams, nextHyperParams);
		
		P initialParams = initializer.initialize(data, numClusters);
		// Pre-allocate space for the next parameters; (TODO: clone() or secondary initializer would be preferable)
		P nextParams = initializer.initialize(data, numClusters);
		ParameterPair<P> paramPair = new ParameterPair<P>(initialParams, nextParams);
		
		ValueAndObject<P> parametersAndLowerbound = aem.optimize(data, altEMAble, optimizer, hyperPair, paramPair);
		P params = parametersAndLowerbound.getObject();

		// Build clustering and predictive models, and cluster!
		ClusteringAndPredictiveModels models = altEMAble.newModelsFrom(params);
		return BasicProbabilisticClustering.newClustering(data, numClusters, models.getClusteringModel(),
				models.getPredictiveModel(), parametersAndLowerbound.getValue());
	}
	
}
